package com.webserver.core;

import com.webserver.http.EmptyRequestException;
import com.webserver.http.HttpRequest;
import com.webserver.http.HttpRseponse;
import com.webserver.servlet.DispatcherServlet;

import java.io.IOException;
import java.net.Socket;

/**
 * 该线程负责与指定客户端完成HTTP协议的交互过程
 *
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run() {

        //测试:读取客户端发送过来的内容
        try {
            //1.解析请求
            HttpRequest request = new HttpRequest(socket);
            //创建响应对象
            HttpRseponse rseponse = new HttpRseponse(socket);
            //2.处理请求
            DispatcherServlet servlet = new DispatcherServlet();
            servlet.service(request,rseponse);
            //3.发送响应
            rseponse.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (EmptyRequestException e) {
          //捕获空请求后无需做任何处理,目的是忽略tey后续操作,直接断开连接
        } finally {
            try {
                //HTTP协议要求交互完毕后断开TCP连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
